// API 服务文件
import type { User, LoginRequest, RegisterRequest } from '@/types'

const API_BASE_URL = 'http://localhost:806'

// 通用请求函数
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  })

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }

  return response.json()
}

// 用户API
export const userAPI = {
  // 获取所有用户
  async getUsers(): Promise<User[]> {
    return request<User[]>('/users')
  },

  // 根据ID获取用户
  async getUserById(id: string): Promise<User> {
    return request<User>(`/users/${id}`)
  },

  // 用户登录验证
  async login(credentials: LoginRequest): Promise<User | null> {
    const users = await request<User[]>(
      `/users?username=${credentials.username}&password=${credentials.password}`
    )
    return users.length > 0 ? users[0] : null
  },

  // 用户注册
  async register(userData: Omit<RegisterRequest, 'confirmPassword'>): Promise<User> {
    const newUser = {
      username: userData.username,
      email: userData.email,
      password: userData.password,
      role: 'student' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      profile: {
        firstName: userData.firstName,
        lastName: userData.lastName,
        avatar: 'https://via.placeholder.com/150',
        phone: userData.phone || '',
      },
    }

    return request<User>('/users', {
      method: 'POST',
      body: JSON.stringify(newUser),
    })
  },

  // 更新用户信息
  async updateUser(id: string, userData: Partial<User>): Promise<User> {
    return request<User>(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify({
        ...userData,
        updatedAt: new Date().toISOString(),
      }),
    })
  },

  // 删除用户
  async deleteUser(id: string): Promise<void> {
    return request<void>(`/users/${id}`, {
      method: 'DELETE',
    })
  },

  // 检查用户名是否存在
  async checkUsername(username: string): Promise<boolean> {
    const users = await request<User[]>(`/users?username=${username}`)
    return users.length > 0
  },

  // 检查邮箱是否存在
  async checkEmail(email: string): Promise<boolean> {
    const users = await request<User[]>(`/users?email=${email}`)
    return users.length > 0
  },
}

// 会话API
export const sessionAPI = {
  // 创建会话（登录）
  async createSession(userId: string): Promise<any> {
    const sessionData = {
      userId,
      createdAt: new Date().toISOString(),
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24小时后过期
    }

    return request<any>('/sessions', {
      method: 'POST',
      body: JSON.stringify(sessionData),
    })
  },

  // 获取用户会话
  async getUserSessions(userId: string): Promise<any[]> {
    return request<any[]>(`/sessions?userId=${userId}`)
  },

  // 删除会话（登出）
  async deleteSession(sessionId: string): Promise<void> {
    return request<void>(`/sessions/${sessionId}`, {
      method: 'DELETE',
    })
  },
}